<?php

namespace app\api\model\v1;


use app\common\exception\Exception;
use app\common\model\Attachment;
use fast\Random;
use think\Model;
use traits\model\SoftDelete;

class User extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'user';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
    ];
    protected function getBirthdayAttr($value,$data){
        return !$value?"":date("Y-m-d",$value);
    }
    protected function getAvatarAttr($value,$data){
        return !$value?"":fiximgurl($value);
    }

    /**登录
     * @param $params
     * @return User|array|bool|\PDOStatement|string|Model|void|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function login($params){
        extract($params);
        if(!$code){
            new Exception("code不能为空");
        }
        //分享人ID
        if(empty($share_id)){
            $share_id = 0;
        }

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$params['xcxappid']."&secret=".$params['xcxsecret']."&js_code=".$code."&grant_type=authorization_code";
        $result = json_decode(file_get_contents($url),true);

        if(!$result['openid']){
            new Exception("微信登录失败");
        }

        $user = User::where(['unionid'=>$result['unionid']])->find();

        $avatarpath = "";
        if($avatar){
            $filename = date("YmdHis").$result['unionid'].".jpg";
            $imginfo = file_get_contents($avatar);
            $path = "uploads/avatar/".$filename;
            $avatarpath = "/".$path;
            file_put_contents($path,$imginfo);
            Attachment::saveFile($filename,$avatarpath,5);
        }
        if(!$user){
            if($share_id){
                $puser = User::get($share_id);
                if(!$puser){
                    new Exception("邀请人不存在");
                }
            }
            $user = new self();
            $user->nickname = $nickname?:"";
            $user->truename = "";
            $user->openid = $result['openid'];
            $user->unionid = $result['unionid'];
            $user->session_key = $result['session_key'];
            $user->token = Random::uuid();
            $user->expiretime = time()+259200;//3天
            $user->createtime = time();
            $user->logintime = time();
            $user->mobile = "";
            $user->avatar = $avatarpath?:"";
            $user->gender = 0;
            $user->birthday = "";
            $user->pid = $share_id;
            $user->xcx_id = $xcxid;
            $user->is_promoter = $is_promoter?intval($is_promoter):0;
            $re = $user->save();
        }else{
            if($avatar){//删除旧头像
                @unlink(".".$user->avatar);
            }
            if($nickname){
                $user->nickname = $nickname;
            }
            if($avatarpath){
                $user->avatar = $avatarpath;
            }
            $user->logintime = time();
            $user->token = Random::uuid();
            $user->expiretime = time()+259200;//3天
            $re = $user->allowField(true)->save();

        }
        if($re){
            return $user;
        }else{
            new Exception("登录失败,请重试");
        }
    }

    /**获取需要返回的用户信息
     * @param $user
     */
    public static function getReturnUserInfo($user){

        return [
            'id' => $user->id,
            'token' => $user->token,
            'nickname' => $user->nickname,
            'truename' => $user->truename,
            'mobile' => $user->mobile,
            'avatar' => fiximgurl($user->avatar),
            'gender' => $user->gender,
            'birthday' => $user->birthday,
            'is_promoter' => $user->is_promoter,
        ];
    }

}
